package com.googlecode.continuity.core.server.service;

import java.util.List;

import org.springframework.dao.support.DataAccessUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.googlecode.continuity.core.client.ContinuityGroup;
import com.googlecode.continuity.core.client.ContinuityUser;

/**
 * GroupServiceHibernate
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class GroupServiceHibernate extends HibernateDaoSupport implements GroupService {
  public ContinuityGroup getGroupById(int id) {
    ContinuityGroup group = (ContinuityGroup) getHibernateTemplate().get(ContinuityGroup.class, id);
    /* TODO: check for existence */
    return group;
  }

  public ContinuityGroup getGroupByName(String name) {
    List<ContinuityGroup> groups = getHibernateTemplate().find("FROM Groups g WHERE name = ?", name);
    /* TODO: check for existence, name is unique */
    return groups.get(0);
  }

  public List<ContinuityGroup> getGroupsByMember(ContinuityUser user) {
    List<ContinuityGroup> groups =
        getHibernateTemplate().find("FROM Groups g NATURAL JOIN Users2Groups u2g WHERE user_id = ?", user.getId());
    return groups;
  }

  public void addMember(ContinuityUser user) {

  }

  public void removeMember(ContinuityUser user) {

  }

  public int getGroupCount() {
    return DataAccessUtils.intResult(getHibernateTemplate().find("select count(*) from Group"));
  }

}
